/**
 * asyncActionCreator.js
 * 创建异步Action的处理函数
 *
 * created by qiuwei
 * version 1.0.0
 * 2016年03月08日
 */

import { HTTP_RESULT } from '../../schema/constants';
import fetch from 'isomorphic-fetch';

export function create(url, request, success, failure, data, onSuccess) {

	return async function(dispatch, getState) {
		dispatch(request());

		let options = undefined;
		if (data) {
			options = {
				method: 'post',
				headers: {
					'Accept': 'application/json',
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(data)
			};
		};

		fetch(`${url}`, options)
			.then((response) => response.json())
			.then((json) => {
				if (json.code === HTTP_RESULT.SUCCESS) {
					dispatch(success(json.data));
					onSuccess && onSuccess(json.data);
				} else {
					dispatch(failure(json.error || json.data));
				}

				if (json) {
					console.log(`请求地址: ${url}`, options);
					console.log(`数据:`, json);
				}
			})
			.catch((error) => {
				dispatch(failure(error.toString()));
			});
	}
}
